/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.joint.finance;

import java.text.DecimalFormat;

/**
 *
 * @author atila
 */
public final class DoubleFormat {

   /**
    * The default format to convert double to String.
    */
   public static final String VALUE_FORMAT_DEF = "#,##0.00";

   private DoubleFormat() {
   }

   /**
    * Converts a double value to a String value. Ex.: converts
    *    <ul><li>32.7 to "32,70"</li>
    *    <li>0.5 to "0,50"</li></ul>
    * @param value a double value
    * @return a String formated.
    */
   public static String fromDoubleToString(double value) {
      return new DecimalFormat(VALUE_FORMAT_DEF).format(value);
   }

   /**
    * Converts a double value to a String value. Ex.: converts
    *    <ul><li>32.7 to "32,70"</li>
    *    <li>0.5 to "0,50"</li></ul>
    * The format value must be like "#,##0.00".
    *    <ul><li>"#,###0.000" if you wish three decimal places</li></ul>
    * @param value a double value
    * @param format the format of the String.
    * @return a String formated.
    */
   public static String fromDoubleToString(double value, String format) {
      return new DecimalFormat(format).format(value);
   }
   /**
    * Converts a String value to a double value. Ex.: converts
    *    <ul><li>"1.230,50" to 1230.5</li>
    *    <li>"45,90" to 45.9</li>
    *    <li>"0,92" to 0.92</il></ul>
    * @param value a String value
    * @return the converted value or 0 (zero), if an exception ocurrs.
    */
   public static double fromStringToDouble(String value) {
      try {
         value = value.replace(".", "");
         value = value.replace(",", ".");
         return Double.parseDouble(value);
      } catch (Exception e) {
         return 0;
      }
   }
}
